<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\TrainTypeModel;
use app\model\course\ware\Courseware as CoursewareModel;
use app\model\plan\PlanCourse;
use think\exception\ValidateException;
use think\Request;

class Course extends AuthController
{
    public function list(Request $request)
    {
        $page = input('page', 1);
        $limit = input('size', 10);

        $where = [];
        $type_id = input('type_id', '');
        $plan_id = input('plan_id', '');
        if ($plan_id) {
            $course_ids = PlanCourse::where('plan_id', $plan_id)
                ->column('course_id');
            $where[] = ['id', 'in', $course_ids];
        }
        $company_id = input('company_id', '');
        if ($company_id || $company_id === 0) {
            $where[] = ['company_id', '=', $company_id];
        }

        $date = input('date', '');
        if ($date) {
            $start = strtotime(date('Y-m-d', strtotime($date[0])) . ' 00:00:00');
            $end = strtotime(date('Y-m-d', strtotime($date[1])) . ' 23:59:59');
            $where[] = ['create_time', 'between', [$start, $end]];
        }

        $data = \app\model\course\course\Course::order('id', 'desc')
            ->with('company')
            ->where($where)
            ->when($course_name = input('course_name'), function ($query) use ($course_name) {
                $query->where('course_name', 'like', '%' . $course_name . '%');
            })
            ->when($type_id, function ($query) use ($type_id) {
                $index = 0;
                foreach ($type_id as $typeID) {
                    if ($index == 0) {
                        $query->where('type_ids', 'like', "%,{$typeID},%");
                    } else {
                        $query->whereOr('type_ids', 'like', "%,{$typeID},%");
                    }
                    $index++;
                }
            })
            ->with('merchantType')
            ->where('status', 1)
            ->paginate($limit)
            ->each(function ($item) {
                if ($item->ware_json && is_array($item->ware_json)) {
                    $item['ware_count'] = count($item['ware_json']);
                } else {
                    $item['ware_count'] = 0;
                }
                $typeIds = explode(',', $item['type_ids']);
                $types = TrainTypeModel::whereIn('id', $typeIds)
                    ->column('title');
                $item->type_name = implode(',', $types);
                $item->company_name = $item['company']['company_name'] ?? '平台';
            });

        return app('json')->success([
            'total' => $data->total(),
            'list' => $data->items(),
        ]);
    }

    public function info(Request $request)
    {
        $trainTypes = DataType::getTrainType();
        $companyTypes = DataType::getCompanyType();
        $id = input('id', '');
        if ($id) {
            $data = \app\model\course\course\Course::getOne($id);
            try {
                $data['selected_type_ids'] = DataType::getTrainTypeRelateIds($data['type_ids']);
                $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
            } catch (\Exception $e) {
                $data['type_ids'] = [];
            }
        } else {
            $data = null;
        }
        // 所有的公司
        $companies = \app\model\company\Company::where('status', 1)
            ->select()
            ->toArray();
        array_unshift($companies, [
            'id' => 0,
            'company_name' => '平台',
        ]);
        $data['course_type'] = $data['course_type'] ?? '';
        $data['require_type'] = $data['require_type'] ?? '';
        return app('json')->success([
            'trainTypes' => $trainTypes,
            'companyTypes' => $companyTypes,
            'data' => $data,
            'companies' => $companies,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'course_name', 'img_url', 'type_ids', 'desc', 'merchant_type_id' => 0,
            'ware_json', 'course_type', 'require_type',
        ]);
        $id = input('id', '');
        try {
            validate([
                'course_name|课程名称' => 'require|max:50',
                'course_type|课程类型' => 'require',
                'require_type|学习需求' => 'require',
                // 'merchant_type_id|企业类型' => 'require'
            ])->check($data);
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
        $data['type_ids'] = ','.implode(',', $data['type_ids']).',';
        $data['resource_type'] = 2;
        if (!$id) {
            $res = \app\model\course\course\Course::create($data);
            $id = $res->id;
        } else {
            \app\model\course\course\Course::update($data, ['id' => $id]);
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        \app\model\course\course\Course::datadelete($id);
        return app('json')->success();
    }

    public function courseList(Request $request)
    {
        $ids = input('ids', '');
        $where = [];
        if (!$ids) {
            $where[] = ['id', '<', 0];
        }

        $data = CoursewareModel::where($where)
            ->when($ids, function ($query) use ($ids) {
                $query->whereIn('id', $ids)
                    ->orderRaw('FIELD(id, ' . implode(',', $ids) . ')');
            })
            ->with('teacher', 'company')
            ->where('status', 1)
            ->select()
            ->each(function ($item) {
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids'] ?? '');
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item->company_name = $item['company']['company_name'] ?? '平台';
                    $item->type_name = implode(',', $types);
                }
            });

        return app('json')->success([
            'list' => $data,
            'total' => count($data)
        ]);
    }
}